package com.fancy.common.utils.lbs;

/**
 * LBS计算两点距离
 * 
 * @author xinfeng.hu 2013-3-13下午12:15:34
 * @version 1.0.0
 * @category 杭州广桥网络技术有限公司(商业先知)
 */
public class LBSDistance {

	// 地球半径。单位:米。
	private static double EARTH_RADIUS = 6371004;

	private double sin(double a) {
		return Math.sin(a);
	}

	private double cos(double a) {
		return Math.cos(a);
	}

	private double acos(double a) {
		return Math.acos(a);
	}

	/**
	 * 转换经纬度为角度的double显示。只处理到小数点后2位(分:60进制)。
	 * */
	private double convert2angle(double a) {
		// 转换60进制为10进制。
		double tem = (long) (a * 100) / 100;
		tem += (a * 100) % 100 / 60;
		double result = tem * Math.PI / 180.0;
		return result;
	}

	private double abs(double a) {
		return Math.abs(a);
	}

	public double computeDistance(double lat1, double lng1, double lat2, double lng2) {
		double OC = cos(convert2angle(lat1));

		double OD = cos(convert2angle(lat2));

		double AC = sin(convert2angle(lat1));

		double BD = sin(convert2angle(lat2));

		// AC=ED
		double BE = abs(BD - AC);

		double lngGap = convert2angle(lng1) - convert2angle(lng2);

		// AE=CD.
		double AE = Math.sqrt(OC * OC + OD * OD - 2 * OC * OD * cos(lngGap));

		double AB = Math.sqrt(AE * AE + BE * BE);

		double angle = acos((2 - AB * AB) / 2);

		double distance = EARTH_RADIUS * angle;

		return distance;
	}

	public static void main(String[] args) {
		LBSDistance l = new LBSDistance();
		System.out.println(l.computeDistance(120.066666666667, 29.3166666666667, 120.066666666667, 29.3116666666667));
	}

}
